package com.example.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

import com.example.constants.MyConstants;

import javax.imageio.stream.FileImageInputStream;

//处理图片的获取和保存至本地
public class PicUtil {

    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return ByteArray
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 设置数据缓冲区
        byte[] buffer = new byte[1024 * 2];
        // 读取到数据的长度
        int len;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();

    }

    /**
     * 根据地址获得数据的字节流
     * @param strUrl 网络连接地址
     * @return
     */
    public static byte[] getImageFromNetByUrl(String strUrl) {
        try {
            InputStream inStream = new FileInputStream(strUrl);// 通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
            inStream.close();
            return btImg;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将图片写入到磁盘
     * @param img 图片数据流
     * @param fileName 文件保存时的名称
     */
    public static void writeImageToDisk(byte[] img, String fileName) {
        try {
            File file = new File(MyConstants.picPath + fileName);
            FileOutputStream fops = new FileOutputStream(file);
            fops.write(img);
            fops.flush();
            fops.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     *
     * @param url 根据视频地址获取二进制数据流，传递给前端
     * @return byte[]
     * @author zs
     * @creed: Talk is cheap,show me the code
     * @date 2021/8/25 11:16
     */
    public static byte[] readInputStream(String url) throws IOException {
        byte[] data = null;
        FileImageInputStream input = new FileImageInputStream(new File(url));
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buf = new byte[1024*1024];
        int numBytesRead = 0;
        while ((numBytesRead = input.read(buf)) != -1) {
            output.write(buf, 0, numBytesRead);
        }
        data = output.toByteArray();
        output.close();
        input.close();
        return data;
    }

}
